package kz.edu.sdu.itech.pcs.client;

import kz.edu.sdu.itech.pcs.common.Client;
import kz.edu.sdu.itech.pcs.common.Permutations;

import org.apache.log4j.Logger;

public class WorkerClient extends Client {
   static Logger log = Logger.getLogger(WorkerClient.class);

   Thread thread;
   public boolean START = false;

   public WorkerClient() {
      thread = new Thread(this);
   }

   public Thread getThread() {
      return thread;
   }

   public void setThread(Thread thread) {
      this.thread = thread;
   }

   public void stopWork() {
      STOP = true;
      START = false;
   }

   public void startWork() {
      START = true;
      STOP = false;
   }

   @Override
   public void run() {
      while (!AppProps.DONE) {
         if (START) {
            START = false;
            status = WORKING;
            current = start;
            count = 0;
            Permutations.setAlphabet(alphabet);
            long last = Math.min(end, Permutations.getPnm(len, alphabet.size()));
            while (!STOP && !AppProps.DONE && current <= last) {
               try {
                  String str = Permutations.getByNum(current, len);
                  int wh = Permutations.hash(str);
                  if (hash == wh) {
                     count++;
//                     log.debug(str);
                  }
                  current++;
                  Thread.sleep(10);
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }
            if (STOP) {
               status = STOPED;
            } else {
               status = DONE;
            }
         } else {
            sleep(1000);
         }
      }
   }

   public void sleep(int x) {
      try {
         Thread.sleep(x);
      } catch (Exception e) {
         // TODO: handle exception
      }
   }
}
